﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using ESOL.Business.Mst;
using ESOL.Business.Fin;
using ESOL.Common;
using ESOL.Common.Entity;
using ESOL.WinUI.MasterData;
using ESOL.WinUI.UICommon;

namespace ESOL.WinUI.Finance
{
    public partial class frmMaintainAccountingVoucher : BaseForm.frmBaseDialogyBusinessForm
    {
        #region Variable
        public FinAccountingVoucherEntity SelectedAccountingVoucher { get; set; }
        private List<FinAccountingVoucherItemEntity> DeleteList = new List<FinAccountingVoucherItemEntity>();
        #endregion

        #region Constructor
        public frmMaintainAccountingVoucher()
        {
            InitializeComponent();
            if (SelectedAccountingVoucher == null)
            {
                SelectedAccountingVoucher = new FinAccountingVoucherEntity();
                SelectedAccountingVoucher.VoucherId = Guid.NewGuid().ToString();
            }
        }
        #endregion

        #region Functions
        private void BindComboBox()
        {
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbStatus, "STATUS", false);
        }
        private void BindDataGridDetail()
        {
            string voucherId = "";
            if (SelectedAccountingVoucher != null)
            {
                voucherId = SelectedAccountingVoucher.VoucherId;
            }
            DataTable dt = FinAccountingVoucherItemBs.GetDataTableByVoucherID(voucherId);
            if (dt == null)
            {
                gvMain.DataSource = null;
                return;
            }
            dt.AcceptChanges();
            gvMain.DataSource = dt;
            DeleteList = new List<FinAccountingVoucherItemEntity>();
        }
        private void ResetTotalAmount()
        {
            decimal totalDebitAmount = 0;
            decimal totalCreditAmount = 0;
            DataTable dt = gvMain.DataSource as DataTable;
            foreach (DataRow dr in dt.Rows)
            {
                if (string.IsNullOrEmpty(dr["DEBIT_AMOUNT"].ToString()) == false)
                {
                    decimal amount = Convert.ToDecimal(dr["DEBIT_AMOUNT"].ToString());
                    totalDebitAmount += amount;
                }
                if (string.IsNullOrEmpty(dr["CREDIT_AMOUNT"].ToString()) == false)
                {
                    decimal amount = Convert.ToDecimal(dr["CREDIT_AMOUNT"].ToString());
                    totalCreditAmount += amount;
                }
            }
            txtTotalDebitAmount.Text = decimal.Round(totalDebitAmount, 2).ToString();
            txtTotalCreditAmount.Text = decimal.Round(totalCreditAmount, 2).ToString();
        }
        private void SetFields()
        {
            BindDataGridDetail();
            if (SelectedAccountingVoucher == null)
            {
                return;
            }
            txtVoucherNo.Text = SelectedAccountingVoucher.VoucherNo;
            if (SelectedAccountingVoucher.AccountingDate.ToString("yyyy-MM-dd") == "1900-01-01" ||
                 SelectedAccountingVoucher.AccountingDate.ToString("yyyy-MM-dd") == "0001-01-01")
            {
                dtpAccountingDate.EditValue = null;
            }
            else
            {
                dtpAccountingDate.EditValue = SelectedAccountingVoucher.AccountingDate;
            }
            cmbStatus.SetSelectedValue(SelectedAccountingVoucher.Status);
            txtTotalDebitAmount.Text = SelectedAccountingVoucher.TotalDebitAmount.ToString("#0.00");
            txtTotalCreditAmount.Text = SelectedAccountingVoucher.TotalCreditAmount.ToString("#0.00");

            UICommonFunctions.SetTextBoxDate(txtCreatedDate, SelectedAccountingVoucher.CreatedDate, "yyyy-MM-dd hh:mm:ss");
            UICommonFunctions.SetTextBoxPersonName(txtCreatedBy, SelectedAccountingVoucher.CreatedBy);
            UICommonFunctions.SetTextBoxDate(txtLastModifiedDate, SelectedAccountingVoucher.LastModifiedDate, "yyyy-MM-dd hh:mm:ss");
            UICommonFunctions.SetTextBoxPersonName(txtLastModifiedBy, SelectedAccountingVoucher.LastModifiedBy);
            UICommonFunctions.SetTextBoxDate(txtApprovedDate, SelectedAccountingVoucher.ApprovedDate, "yyyy-MM-dd hh:mm:ss");
            UICommonFunctions.SetTextBoxPersonName(txtApprovedBy, SelectedAccountingVoucher.ApprovedBy);
        }
        private void SetEntity()
        {
            SelectedAccountingVoucher.VoucherNo = txtVoucherNo.Text;
            if (dtpAccountingDate.EditValue != null)
            {
                SelectedAccountingVoucher.AccountingDate = Convert.ToDateTime(dtpAccountingDate.EditValue.ToString());
            }
            if (ThisActionType == ActionType.New || ThisActionType == ActionType.Modify)
            {
                SelectedAccountingVoucher.Status = NormalStatus.STATUS02.ToString();
            }
            SelectedAccountingVoucher.TotalDebitAmount = CommonFunctions.ToDecimal(txtTotalDebitAmount.Text);
            SelectedAccountingVoucher.TotalCreditAmount = CommonFunctions.ToDecimal(txtTotalCreditAmount.Text);

            if (ThisActionType == ActionType.New)
            {
                SelectedAccountingVoucher.CreatedDate = DateTime.Now;
                SelectedAccountingVoucher.CreatedBy = CommonParameter.CurrentUser.PersonId;
            }
            if (ThisActionType == ActionType.New || ThisActionType == ActionType.Modify)
            {
                SelectedAccountingVoucher.LastModifiedDate = DateTime.Now;
                SelectedAccountingVoucher.LastModifiedBy = CommonParameter.CurrentUser.PersonId;
            }
        }
        private bool CheckData()
        {
            if (string.IsNullOrEmpty(txtVoucherNo.Text))
            {
                MessageBox.Show("编号不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (dtpAccountingDate.EditValue == null)
            {
                MessageBox.Show("记账日期不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            DataTable dt = gvMain.DataSource as DataTable;
            if (dt == null || dt.Rows.Count == 0)
            {
                MessageBox.Show("记账明细不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (CommonFunctions.ToDecimal(txtTotalCreditAmount.Text) != CommonFunctions.ToDecimal(txtTotalDebitAmount.Text))
            {
                MessageBox.Show("借方总金额和贷方总金额必须相等！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            return true;
        }
        private bool Save()
        {
            try
            {
                if (CheckData() == false)
                {
                    return false;
                }
                if (ThisActionType == ActionType.New)
                {
                    SetEntity();
                    DataTable dt = (DataTable)gvMain.DataSource;
                    bool isSuccessful = FinAccountingVoucherBs.SaveAccountingVoucher(true, SelectedAccountingVoucher, dt, DeleteList);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("新增失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                else if (ThisActionType == ActionType.Modify)
                {
                    SetEntity();
                    DataTable dt = (DataTable)gvMain.DataSource;
                    bool isSuccessful = FinAccountingVoucherBs.SaveAccountingVoucher(false, SelectedAccountingVoucher, dt, DeleteList);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("修改失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                else if (ThisActionType == ActionType.Approve)
                {
                    SelectedAccountingVoucher.ApprovedDate = DateTime.Now;
                    SelectedAccountingVoucher.ApprovedBy = CommonParameter.CurrentUser.PersonId;
                    bool isSuccessful = FinAccountingVoucherBs.UpdateFinAccountingVoucher(SelectedAccountingVoucher);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("审核失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
        }
        #endregion

        #region Event
        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);
            BindComboBox();
            if (ThisActionType != ActionType.New)
            {
                SetFields();
            }
        }

        protected override void Click_Save()
        {
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
        }
        protected override void Click_SaveNew()
        {
            if (Save())
            {
                ThisActionType = ActionType.New;
                SelectedAccountingVoucher = new FinAccountingVoucherEntity();
                SelectedAccountingVoucher.VoucherId = Guid.NewGuid().ToString();
                SetFields();
            }
        }
        protected override void Click_Approve()
        {
            if (SelectedAccountingVoucher == null)
            {
                return;
            }
            SelectedAccountingVoucher.Status = NormalStatus.STATUS03.ToString();
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
        }
        protected override void Click_Reject()
        {
            if (SelectedAccountingVoucher == null)
            {
                return;
            }
            SelectedAccountingVoucher.Status = NormalStatus.STATUS04.ToString();
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
        }
        private void tsmNewLine_Click(object sender, EventArgs e)
        {
            if (gvMain.DataSource == null)
            {
                BindDataGridDetail();
            }
            if (gvMain.DataSource == null)
            {
                return;
            }
            DataTable dt = (DataTable)gvMain.DataSource;
            DataRow dr = dt.NewRow();
            dr["ITEM_ID"] = Guid.NewGuid().ToString();
            dr["VOUCHER_ID"] = SelectedAccountingVoucher.VoucherId;
            dt.Rows.Add(dr);

           
            
        }

        private void tsmDelLine_Click(object sender, EventArgs e)
        {
            if (gvMain.DataSource == null)
            {
                BindDataGridDetail();
            }
            if (gvMain.DataSource == null)
            {
                return;
            }
            if (drSelected.RowState != DataRowState.Added)
            {
                FinAccountingVoucherItemEntity entity = new FinAccountingVoucherItemEntity(drSelected);
                DeleteList.Add(entity);
            }
            DataTable dt = gvMain.DataSource as DataTable;
            dt.Rows.Remove(drSelected);
            ResetTotalAmount();
        }

        private void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.Column.FieldName.Equals("DEBIT_AMOUNT")
                || e.Column.FieldName.Equals("CREDIT_AMOUNT"))
            {
                ResetTotalAmount();
            }
        }

        private void repositoryItemButtonEdit1_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainFinanceAccountsCodeQuery frm = new frmMaintainFinanceAccountsCodeQuery();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedAccount != null)
            {
                FinAccountsEntity parent = FinAccountsBs.GetByCode(frm.SelectedAccount.ParentCode);
                drSelected["ACCOUNTS_CODE"] = frm.SelectedAccount.AccountsCode;
                drSelected["PARENT_ACCOUNTS_NAME"] = "";
                if (parent != null)
                {
                    drSelected["PARENT_ACCOUNTS_NAME"] = parent.AccountsName;
                }
                drSelected["ACCOUNTS_NAME"] = frm.SelectedAccount.AccountsName;
            }
        }
      
        DataRow drSelected;
        private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            drSelected = gridView1.GetDataRow(e.FocusedRowHandle);
        }

        #endregion

    }
}
